package com.youdoneed.friends.friends;

import com.querydsl.core.types.Projections;
import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLInsertClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.AESEncryptor;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.base.common.JsonConverter;
import com.youdoneed.community.feign.ForumClient;
import com.youdoneed.friends.Const.CoolfaceNoticeType;
import com.youdoneed.friends.coolface.FaceSearchService;
import com.youdoneed.friends.model.Contact;
import com.youdoneed.friends.model.FaceSearch;
import com.youdoneed.friends.model.Friends;
import com.youdoneed.friends.model.FriendsConfirm;
import com.youdoneed.friends.query.QContact;
import com.youdoneed.friends.query.QFriends;
import com.youdoneed.friends.query.QFriendsConfirm;
import com.youdoneed.friends.query.QRemoveRecommendFriends;
import com.youdoneed.friends.vo.*;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.CoolfaceNotice;
import com.youdoneed.user.model.User;
import com.youdoneed.user.vo.ContactUser;
import com.youdoneed.user.vo.UserShow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class FriendsService {

    private final Logger logger = LoggerFactory.getLogger(FriendsService.class);

    @Autowired
    private SQLQueryFactory queryFactory;
    private QFriends qFriends = QFriends.Friends;
    private QFriends qFriends2 = new QFriends("Friends2");
    private QRemoveRecommendFriends qRemoveRecommendFriends = QRemoveRecommendFriends.RemoveRecommendFriends;
    private QFriendsConfirm qFriendsConfirm = QFriendsConfirm.FriendsConfirm;
    private QContact qContact = QContact.Contact;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ForumClient forumClient;

    @Autowired
    private FaceSearchService faceSearchService;

    @Autowired
    private RemoveRecommendFriendsService removeRecommendFriendsService;

    @Autowired
    private FriendsConfirmService friendsConfirmService;

    public Long getFriendsCount(String userId){
        return queryFactory.selectDistinct(qFriends.friendId)
                .from(qFriends)
                .where(qFriends.userId.eq(userId))
                .where(qFriends.blBlack.eq(1))
                .fetchCount();
    }

    /**
     * 获取好友对象
     */
    public Friends getFriends(String userId, String friendId) {
        return queryFactory.selectFrom(qFriends)
                .where(qFriends.userId.eq(userId))
                .where(qFriends.friendId.eq(friendId))
                .fetchOne();
    }

    /**
     * 插入一条好友记录
     */
    public long insertFriends(Friends friends) {
        if (!StringUtils.hasText(friends.getFriendId())) {
            friends.setFriendId(GlobalIdWorker.nextString());
        }
        friends.setBlBlack(1);
        friends.setCreateTime(new Date());
        return queryFactory.insert(qFriends)
                .populate(friends)
                .execute();
    }

    /**
     * 保存好友到数据库
     */
    public void saveFriends(String userId, String friendId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (!StringUtils.hasText(friendId)) {
            throw new AppException("好友ID不能为空");
        }

        if (userId.equals(friendId)) {
            throw new AppException("您不能添加自己为好友");
        }

        // 查看已存在的好友
        Friends friendsOld = getFriends(userId, friendId);
        if (friendsOld != null) {
            if (friendsOld.getBlBlack().equals(0)) {
                throw new AppException("黑名单用户不能添加为好友");
            } else {
                throw new AppException("该用户已经是您的好友了");
            }
        }

        // 保存我的好友
        Friends friends = new Friends();
        friends.setUserId(userId);
        friends.setFriendId(friendId);
        insertFriends(friends);
        userFeignClient.totalFriendChange(userId, 1);
        // 对方也保存好友
        Friends record = new Friends();
        record.setUserId(friendId);
        record.setFriendId(userId);
        insertFriends(record);
        userFeignClient.totalFriendChange(friendId, 1);
        // 好友动态相互关注
        forumClient.saveUserAttention(userId, friendId);
        forumClient.saveUserAttention(friendId, userId);
    }

    /**
     * 查询共同好友数
     */
    public DataCounts mutualFriendsCount(String userId, String... friendIds) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (friendIds == null || friendIds.length == 0) {
            return new DataCounts();
        }
        List<DataCounts.Count> counts = queryFactory.select(
                Projections.bean(DataCounts.Count.class,
                        qFriends2.userId.as("id"),
                        qFriends.friendId.count().as("count")))
                .from(qFriends)
                .join(qFriends2)
                .on(qFriends.friendId.eq(qFriends2.friendId))
                .where(qFriends.userId.eq(userId))
                .where(qFriends2.userId.in(friendIds))
                .where(qFriends.blBlack.eq(1))
                .where(qFriends2.blBlack.eq(1))
                .groupBy(qFriends2.userId)
                .fetch();
        return new DataCounts(counts);
    }

    /**
     * 更新用户通讯录。
     */
    public long updateContacts(String userId, Contact[] contacts) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }

        //新注册用户直接添加通讯录中的好友
        if (0 == contacts.length) {
            return 0L;
        }
        String[] phones = new String[contacts.length];
        for (int index = 0; index < contacts.length; index++) {
            phones[index] = contacts[index].getPhoneNo();
        }

        Long contactUserCount = queryFactory.selectFrom(qContact)
                .where(qContact.userId.eq(userId)).fetchCount();
        logger.info("contactUserCount:"+ contactUserCount);
        if (contactUserCount < 1) {
            logger.info("保存通讯录中已注册用户的好友关系");
            //用户第一次导入手机通讯录，保存通讯录中已注册用户的好友关系
            List<String> phoneBookFriendIds = userFeignClient.findUserIdsByPhoneNos(phones).getData();
            logger.info("phoneBookFriendIds.size():"+phoneBookFriendIds.size());
            //获取我的好友列表
            List<String> myFriendIds = this.findFriendIds(userId, null);
            Iterator<String> iterator = phoneBookFriendIds.iterator();
            while(iterator.hasNext()){
                String id = iterator.next();
                if(myFriendIds.contains(id)){
                    iterator.remove();
                }
            }

            //批量插入好友记录
            SQLInsertClause insert = queryFactory.insert(qFriends);
            Date createDate = new Date();
            for(String friendId : phoneBookFriendIds){
                Friends friends = new Friends();
                friends.setBlBlack(1);
                friends.setCreateTime(createDate);
                friends.setFriendId(friendId);
                friends.setUserId(userId);

                Friends friends2 = new Friends();
                friends2.setBlBlack(1);
                friends2.setCreateTime(createDate);
                friends2.setFriendId(userId);
                friends2.setUserId(friendId);

                insert.populate(friends).addBatch();
                insert.populate(friends2).addBatch();
            }
            insert.execute();
            //保存用户之间的相互关注
            forumClient.saveAttentionInBatch(userId, phoneBookFriendIds);
            //发送通知
            forumClient.saveNoticeInBatch(userId, phoneBookFriendIds);

        }

        // 清空该用户的通讯录
        queryFactory.delete(qContact)
                .where(qContact.userId.eq(userId))
                .execute();
        // 批量添加通讯录
        SQLInsertClause insert = queryFactory.insert(qContact);
        for (Contact contact : contacts) {
            contact.setUserId(userId);
            contact.setContactId(GlobalIdWorker.nextString());
            contact.setCreateTime(new Timestamp(System.currentTimeMillis()));
            contact.setName(AESEncryptor.encryptString(contact.getName()));
            contact.setPhoneNo(AESEncryptor.encryptString(contact.getPhoneNo()));
            insert.populate(contact)
                    .addBatch();
        }
        return insert.isEmpty() ? 0L : insert.execute();
    }

    /**
     * 获取用户联系人号码。
     */
    public List<Contact> getContacts(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        List<Contact> contacts = queryFactory.selectFrom(qContact)
                .where(qContact.userId.eq(userId))
                .fetch();
        contacts.forEach(contact -> {
            contact.setName(AESEncryptor.decryptString(contact.getName()));
            contact.setPhoneNo(AESEncryptor.decryptString(contact.getPhoneNo()));
        });
        return contacts;
    }

    /**
     * 好友关系处理结果
     */
    public class HandleResult {
        /**
         * 好友标识：0.非好友但对方加我为好友 1.已经是好友
         * 2.非好友且没有好友请求 3.非好友但我加对方为好友 4.是我自己
         */
        public Integer handleFlag;
        public String confirmId;
    }

    /**
     * 好友关系处理方法
     */
    public HandleResult getFriendHandle(String userId, String friendId) {
        HandleResult result = new HandleResult();
        // 是否我的好友
        if (userId.equals(friendId)) {
            // 是自己啊
            result.handleFlag = 4;
        } else if (queryFactory.selectFrom(qFriends)
                .where(qFriends.userId.eq(userId))
                .where(qFriends.friendId.eq(friendId))
                .where(qFriends.blBlack.eq(1))
                .fetchCount() > 0) {
            result.handleFlag = 1;
        } else {
            FriendsConfirm friendsConfirm;
            if ((friendsConfirm = queryFactory.selectFrom(qFriendsConfirm)
                    .where(qFriendsConfirm.userId.eq(userId))
                    .where(qFriendsConfirm.friendId.eq(friendId))
                    .where(qFriendsConfirm.handleFlag.eq(0))
                    .fetchFirst()) != null) {
                // 我已经发起加好友请求
                result.handleFlag = 3;
                result.confirmId = friendsConfirm.getConfirmId();
            } else if ((friendsConfirm = queryFactory.selectFrom(qFriendsConfirm)
                    .where(qFriendsConfirm.userId.eq(friendId))
                    .where(qFriendsConfirm.friendId.eq(userId))
                    .where(qFriendsConfirm.handleFlag.eq(0))
                    .fetchFirst()) != null) {
                // 存在加我为好友的请求
                result.handleFlag = 0;
                result.confirmId = friendsConfirm.getConfirmId();
            } else {
                // 不存在任何好友请求
                result.handleFlag = 2;
            }
        }
        return result;
    }

    /**
     * 我的好友列表或好友的好友列表
     */
    public List<FindFriendsVO> findFriendsList(String userId, String friendId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        List<FindFriendsVO> friendsVOS = new ArrayList<>();

        SQLQuery<Friends> query = queryFactory.selectFrom(qFriends)
                .where(qFriends.blBlack.eq(1));
        // 查询好友的好友
        if (StringUtils.hasText(friendId)) {
            User friend = userFeignClient.getUser(friendId).getData();
            if (friend.getAllowMyFriends() == 0) { // 禁止查看
                throw new AppException("您不能查看该用户的好友列表！");
            } else if (friend.getAllowMyFriends() == 2) { // 仅好友
                if (isFriendOrNot(userId, friendId).isEmpty()) {
                    throw new AppException("您不能查看该用户的好友列表！");
                }
            }
            query.where(qFriends.userId.eq(friendId));
            // 第一条仅表示我和该好友的信息
            FindFriendsVO friendsVO = new FindFriendsVO();
            friendsVO.setMutualFriendCount(mutualFriendsCount(userId, friendId).getCount(friendId));
            // 查看好友的好友列表需要好友关系
            if (StringUtils.hasText(friendId)) {
                HandleResult result = getFriendHandle(userId, friendId);
                friendsVO.setHandleFlag(result.handleFlag);
                friendsVO.setConfirmId(result.confirmId);
            } else {
                friendsVO.setHandleFlag(1);
            }
            friendsVOS.add(friendsVO);
        } else {
            query.where(qFriends.userId.eq(userId));
        }
        List<Friends> friendsList = query.fetch();
        // 获取全部好友用户信息
        List<User> users = userFeignClient.getUsers(
                friendsList.stream().map(Friends::getFriendId).toArray(String[]::new)).getData();
        String[] friendIds = friendsList.stream().map(Friends::getFriendId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, friendIds);

        // 处理我的好友或者好友的好友关系
        for (Friends friends : friendsList) {
            for (User user : users) {
                if (user.getUserId().equals(friends.getFriendId())) {
                    FindFriendsVO friendsVO = new FindFriendsVO();
                    friendsVO.setUser(user);
                    friendsVO.setMutualFriendCount(counts.getCount(friends.getFriendId()));
                    // 查看好友的好友列表需要好友关系
                    if (StringUtils.hasText(friendId)) {
                        HandleResult result = getFriendHandle(userId, friends.getFriendId());
                        friendsVO.setHandleFlag(result.handleFlag);
                        friendsVO.setConfirmId(result.confirmId);
                    } else {
                        friendsVO.setHandleFlag(1);
                    }
                    friendsVOS.add(friendsVO);
                    break; // 该结束内层循环了
                }
            }
        }
        return friendsVOS;
    }

    /**
     * 根据用户ID查找好友
     */
    public List<User> findFriends(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        List<String> friendIds = queryFactory.select(qFriends.friendId)
                .from(qFriends)
                .where(qFriends.userId.eq(userId))
                .where(qFriends.blBlack.eq(1))
                .fetch();
        return userFeignClient.getUsers(friendIds.toArray(
                new String[friendIds.size()])).getData();
    }

    /**
     * 根据用户ID查找好友ID
     */
    public List<String> findFriendIds(String userId, Integer blBlack) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        SQLQuery<String> query = queryFactory.select(qFriends.friendId)
                .from(qFriends)
                .where(qFriends.userId.eq(userId));
        if (blBlack != null) {
            query.where(qFriends.blBlack.eq(blBlack));
        }
        return query.fetch();
    }

    /**
     * 删除或拉黑好友
     */
    public void updateFriends(String userId, String friendId, Integer blBlack, Integer blDelete) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (!StringUtils.hasText(friendId)) {
            throw new AppException("好友ID不能为空");
        }

        // 拉黑好友，一方拉黑则双方互黑
        if (blBlack != null && blBlack.equals(0)) {
            queryFactory.update(qFriends)
                    .set(qFriends.blBlack, 0)
                    .where((qFriends.userId.eq(userId).and(qFriends.friendId.eq(friendId)))
                            .or(qFriends.userId.eq(friendId).and(qFriends.friendId.eq(userId))))
                    .execute();
        } else if (blDelete != null && blDelete.equals(0)) {
            // 删除好友，一方删除则双方都删除
            queryFactory.delete(qFriends)
                    .where((qFriends.userId.eq(userId).and(qFriends.friendId.eq(friendId)))
                            .or(qFriends.userId.eq(friendId).and(qFriends.friendId.eq(userId))))
                    .execute();
        } else {
            throw new AppException("请指定正确的好友处理操作");
        }

        // 清空已有的好友请求
        queryFactory.delete(qFriendsConfirm)
                .where((qFriendsConfirm.userId.eq(userId).and(qFriendsConfirm.friendId.eq(friendId)))
                        .or(qFriendsConfirm.userId.eq(friendId).and(qFriendsConfirm.friendId.eq(userId))))
                .execute();
        // 好友数减少、取消关注
        userFeignClient.totalFriendChange(userId, -1);
        userFeignClient.totalFriendChange(friendId, -1);
        forumClient.deleteUserAttentionForFriends(userId, friendId);
        forumClient.deleteUserAttentionForFriends(friendId, userId);
    }

    /**
     * 查询共同好友
     */
    public List<FindMutualFriendsVO> findCommonFriends(String userId, String friendId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (!StringUtils.hasText(friendId)) {
            throw new AppException("好友ID不能为空");
        }

        List<Friends> mutualFriends = queryFactory.selectFrom(qFriends)
                .join(qFriends2)
                .on(qFriends.friendId.eq(qFriends2.friendId))
                .where(qFriends.userId.eq(userId))
                .where(qFriends2.userId.eq(friendId))
                .where(qFriends.blBlack.eq(1))
                .where(qFriends2.blBlack.eq(1))
                .fetch();

        String[] friendIds = mutualFriends.stream().map(Friends::getFriendId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, friendIds);

        List<FindMutualFriendsVO> mutualFriendsVOS = new ArrayList<>();
        for (Friends friends : mutualFriends) {
            FindMutualFriendsVO mutualFriendsVO = new FindMutualFriendsVO();
            mutualFriendsVO.setMutualFriendCount(counts.getCount(friends.getFriendId()));
            mutualFriendsVO.setUser(userFeignClient.getUser(friends.getFriendId()).getData());
            mutualFriendsVOS.add(mutualFriendsVO);
        }
        return mutualFriendsVOS;
    }

    /**
     * 查询好友的好友
     */
    public RecommendsFriends findFriendsOfFiend(RecommendFriendsParam param, String userId) {
        // 参数校验、部分参数有默认值
        if (param == null || !StringUtils.hasText(userId)) {
            throw new AppException("查询参数不能为空");
        }

        // 查找好友ID、包括黑名单ID
        List<String> notShowIds = findFriendIds(userId, null);
        notShowIds.add(userId);

        // 推荐该好友的好友给我
        RecommendsFriends recommendsFriends = new RecommendsFriends();
        // 该好友的好友
        List<String> friendsFriendIds = queryFactory.selectDistinct(qFriends.friendId)
                .from(qFriends)
                // 排除已经点击移除的用户
                .leftJoin(qRemoveRecommendFriends)
                .on(qRemoveRecommendFriends.userId.eq(userId)
                        .and(qRemoveRecommendFriends.friendId.eq(qFriends.friendId)))
                .where(qRemoveRecommendFriends.removeRecommendId.isNull())
                // 排除存在好友请求的，别人加我或我加别人
                .leftJoin(qFriendsConfirm)
                .on(qFriendsConfirm.userId.eq(qFriends.friendId)
                        .and(qFriendsConfirm.friendId.eq(userId))
                        .or(qFriendsConfirm.userId.eq(userId)
                                .and(qFriendsConfirm.friendId.eq(qFriends.friendId))))
                .where(qFriendsConfirm.confirmId.isNull())
                // 查询条件开始
                .where(qFriends.userId.eq(param.getFriendId()))
                .where(qFriends.blBlack.eq(1))
                // 移除我的好友及黑名单
                .where(qFriends.friendId.notIn(notShowIds))
                .fetch();
        // 查询用户信息
        List<User> users = userFeignClient.getUsers(friendsFriendIds
                .toArray(new String[friendsFriendIds.size()])).getData();

        String[] friendIds = users.stream().map(User::getUserId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, friendIds);

        for (User user : users) {
            RecommendsFriends.UserInfo userInfo = new RecommendsFriends.UserInfo();
            userInfo.setUser(user);
            userInfo.setRegisterTime(user.getCreateTime().getTime());
            userInfo.setHandleFlag(2);
            userInfo.setMutualFriendCount(counts.getCount(user.getUserId()));
            recommendsFriends.getFriendsList().add(userInfo);
            // 根据共同好友数降序
            recommendsFriends.getFriendsList().sort(Comparator.comparing(
                    RecommendsFriends.UserInfo::getMutualFriendCount).reversed());
        }
        return recommendsFriends;
    }

    /**
     * 查询推荐用户：共同好友和通讯录用户
     */
    public RecommendsFriends findRecommendFriends(RecommendFriendsParam param, String userId) {

        // 参数校验、部分参数有默认值
        if (param == null || !StringUtils.hasText(userId)) {
            throw new AppException("查询参数不能为空");
        }
        // 结束条、开始条、正在取第几条
        int endRow = param.getCurrentPage() * param.getRows();
        int startRow = endRow - param.getRows();
        int index = 0;

        // 查找好友ID、包括黑名单ID
        List<String> notShowIds = findFriendIds(userId, null);
        notShowIds.add(userId);
        // 排除已经点击移除的用户
        notShowIds.addAll(queryFactory.selectDistinct(qRemoveRecommendFriends.friendId)
                .from(qRemoveRecommendFriends)
                .where(qRemoveRecommendFriends.userId.eq(userId)).fetch());
        // 推荐我好友的好友及通讯录好友
        RecommendsFriends recommendsFriends = new RecommendsFriends();

        // 查询通讯录的好友
        List<String> contactNos = getContacts(userId).stream()
                .map(Contact::getPhoneNo).collect(Collectors.toList());
        if (contactNos.size() > 0) {
            // 查询用户信息
            List<User> phoneUsers = userFeignClient.findByPhoneNos(contactNos
                    .toArray(new String[contactNos.size()])).getData();

            String[] phoneFriendIds = phoneUsers.stream().map(User::getUserId).toArray(String[]::new);
            DataCounts phoneMutualCounts = mutualFriendsCount(userId, phoneFriendIds);

            // 取所有通讯录已注册的用户
            List<RecommendsFriends.UserInfo> allPhoneUsers = new ArrayList<>();
            for (User user : phoneUsers) {
                if (notShowIds.contains(user.getUserId()))
                    continue;
                RecommendsFriends.UserInfo userInfo = new RecommendsFriends.UserInfo();
                userInfo.setUser(user);
                userInfo.setRegisterTime(user.getCreateTime().getTime());
                // 处理好友关系
                HandleResult result = getFriendHandle(userId, user.getUserId());
                if (result.handleFlag == 0 || result.handleFlag == 3)
                    continue;
                userInfo.setHandleFlag(result.handleFlag);
                userInfo.setConfirmId(result.confirmId);
                userInfo.setMutualFriendCount(phoneMutualCounts.getCount(user.getUserId()));
                allPhoneUsers.add(userInfo);
            }
            // 根据注册时间降序
            allPhoneUsers.sort(Comparator.comparing(
                    RecommendsFriends.UserInfo::getRegisterTime).reversed());
            // 根据共同好友数降序
            allPhoneUsers.sort(Comparator.comparing(
                    RecommendsFriends.UserInfo::getMutualFriendCount).reversed());

            // 添加到结果列表
            for (RecommendsFriends.UserInfo userInfo : allPhoneUsers) {
                if (index < startRow) continue;
                if (index++ >= endRow) return recommendsFriends;
                recommendsFriends.getFriendsListByPhone().add(userInfo);
            }

            // 好友的好友去掉通讯录推荐好中已有的
            allPhoneUsers.forEach(userInfo -> notShowIds.add(userInfo.getUser().getUserId()));
        }
        // 查询好友的好友
        List<String> friendsFriendIds = queryFactory.selectDistinct(qFriends.friendId)
                .from(qFriends).leftJoin(qFriends2)
                .on(qFriends.userId.eq(qFriends2.friendId))
                // 排除存在好友请求的，别人加我或我加别人
                .leftJoin(qFriendsConfirm)
                .on(qFriendsConfirm.userId.eq(qFriends.friendId)
                        .and(qFriendsConfirm.friendId.eq(userId))
                        .or(qFriendsConfirm.userId.eq(userId)
                                .and(qFriendsConfirm.friendId.eq(qFriends.friendId))))
                .where(qFriendsConfirm.confirmId.isNull())
                // 查询条件开始
                .where(qFriends2.userId.eq(userId))
                .where(qFriends.blBlack.eq(1))
                .where(qFriends2.blBlack.eq(1))
                // 移除我的好友及黑名单
                .where(qFriends.friendId.notIn(notShowIds))
                .limit(1000)
                .fetch();

        // 查询用户信息
        List<User> users = userFeignClient.getUsers(friendsFriendIds
                .toArray(new String[friendsFriendIds.size()])).getData();

        String[] friendIds = users.stream().map(User::getUserId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, friendIds);
        // 取所有好友的好友
        List<RecommendsFriends.UserInfo> allFriendsUsers = new ArrayList<>();
        for (User user : users) {
            RecommendsFriends.UserInfo userInfo = new RecommendsFriends.UserInfo();
            userInfo.setUser(user);
            if (null != user.getCreateTime()) {
                userInfo.setRegisterTime(user.getCreateTime().getTime());
            } else {
                userInfo.setRegisterTime((new Date()).getTime());
                ;
            }
            userInfo.setHandleFlag(2);
            userInfo.setMutualFriendCount(counts.getCount(user.getUserId()));
            allFriendsUsers.add(userInfo);
        }
        // 根据共同好友数降序
        allFriendsUsers.sort(Comparator.comparing(
                RecommendsFriends.UserInfo::getMutualFriendCount).reversed());

        // 添加到结果列表
        for (RecommendsFriends.UserInfo userInfo : allFriendsUsers) {
            if (index < startRow) continue;
            if (index++ >= endRow) return recommendsFriends;
            recommendsFriends.getFriendsList().add(userInfo);
        }
        return recommendsFriends;
    }

    /**
     * 判断是否是好友和是否已关注
     */
    public FriendOrFocusVO isFriendOrFocus(String userId, String friendId) {
        FriendOrFocusVO friendOrFocusVO = new FriendOrFocusVO();
        // 处理好友关系
        HandleResult result = getFriendHandle(userId, friendId);
        friendOrFocusVO.setHandleFlag(result.handleFlag);
        friendOrFocusVO.setConfirmId(result.confirmId);
        String flag = forumClient.isFocusOrNot(userId, friendId).getData();
        //0为没有关注，1为已经关注
        friendOrFocusVO.setFocusFlag("true".equals(flag) ? 1 : 0);
        return friendOrFocusVO;
    }

    /**
     * 查询是我的好友的ID
     */
    public List<String> isFriendOrNot(String userId, String... friendIds) {
        if (friendIds.length == 0 || !StringUtils.hasText(userId)) {
            throw new AppException("传入参数错误！");
        }
        return queryFactory.select(qFriends.friendId)
                .from(qFriends)
                .where(qFriends.userId.eq(userId))
                .where(qFriends.friendId.in(friendIds))
                .where(qFriends.blBlack.eq(1))
                .fetch();
    }

    /**
     * 通讯录好友查询
     * @author youyuan
     */
    public PhoneAddressVO findAddressByPhone(String userId, List<User> userList) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (userList == null || userList.isEmpty()) {
            return new PhoneAddressVO();
        }

        // 获取通讯录用户手机号
        String[] phoneNos = userList.stream().map(User::getPhoneNo).toArray(String[]::new);

        // 根据手机通讯录查询注册用户
        List<User> registeredUsers = userFeignClient.findByPhoneNos(phoneNos).getData();
        // 筛选出未注册用户
        List<User> unregisteredUsers = new ArrayList<>();
        List<String> unregisteredPhoneNos = new ArrayList<>();
        boolean unregistered;
        for (User user : userList) {
            unregistered = true;
            for (User registeredUser : registeredUsers) {
                if (registeredUser.getPhoneNo().equals(user.getPhoneNo())) {
                    unregistered = false;
                    break;
                }
            }
            if (unregistered) {
                unregisteredUsers.add(user);
                unregisteredPhoneNos.add(user.getPhoneNo());
            }
        }
        // 今天邀请过的手机号
        List<String> invitedPhoneNos = userFeignClient.hasInvitedToday(unregisteredPhoneNos
                .toArray(new String[unregisteredPhoneNos.size()])).getData();
        // 处理结果汇总
        PhoneAddressVO phoneAddressVO = new PhoneAddressVO();

        for (User user : unregisteredUsers) {
            PhoneAddressVO.UnregisteredUser unregisteredUser = new PhoneAddressVO.UnregisteredUser();
            unregisteredUser.setUser(user);
            unregisteredUser.setHasInvite(invitedPhoneNos.contains(user.getPhoneNo()) ? 1 : 0);
            phoneAddressVO.getUnregisteredUsers().add(unregisteredUser);
        }
        // 查找好友ID、包括黑名单ID
        List<String> friendIds = findFriendIds(userId, null);
        String[] registeredIds = registeredUsers.stream().map(User::getUserId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, registeredIds);
        for (User user : registeredUsers) {
            if (userId.equals(user.getUserId())) {
                continue;
            }
            if (friendIds.contains(user.getUserId())) {
                continue;
            }
            PhoneAddressVO.RegisteredUser registeredUser = new PhoneAddressVO.RegisteredUser();
            registeredUser.setUser(user);
            registeredUser.setMutualFriendCount(counts.getCount(user.getUserId()));
            // 处理好友关系
            HandleResult result = getFriendHandle(userId, user.getUserId());
            registeredUser.setHandleFlag(result.handleFlag);
            registeredUser.setConfirmId(result.confirmId);
            phoneAddressVO.getRegisteredUsers().add(registeredUser);
        }

        List<PhoneAddressVO.RegisteredUser> list = phoneAddressVO.getRegisteredUsers();
        Iterator<PhoneAddressVO.RegisteredUser> iterator = list.iterator();
        while (iterator.hasNext()) {
            PhoneAddressVO.RegisteredUser registeredUser = iterator.next();
            if (null == registeredUser) {
                iterator.remove();
            }

            if (null == registeredUser.getMutualFriendCount()) {
                registeredUser.setMutualFriendCount(0L);
            }
        }

        if (0 < list.size()) {
            list.sort(Comparator.comparing(
                    PhoneAddressVO.RegisteredUser::getMutualFriendCount).reversed());
        }

        return phoneAddressVO;
    }

    /**
     * 获取手机通讯录好友
     * @param userId
     * @return PhoneAddressVO
     * @author lid
     * @date 2018.1.5
     */
    public PhoneAddressVO findPhoneFriendsByPhone(Integer rows, Integer currentPage, String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }

        if((null == rows)
                || (null == currentPage)){
            return new PhoneAddressVO();
        }

        List<Contact> listContact = this.getContacts(userId);
        if((null == listContact)
                || (0 == listContact.size())){
            return new PhoneAddressVO();
        }
        // 获取通讯录用户手机号
        String[] phoneNos = listContact.stream().map(Contact::getPhoneNo).toArray(String[]::new);

        // 根据手机通讯录查询注册用户
        List<User> registeredUsers = userFeignClient.findByPhoneNos(phoneNos).getData();
        // 筛选出未注册用户
        List<User> unregisteredUsers = new ArrayList<>();
        List<String> unregisteredPhoneNos = new ArrayList<>();
        boolean unregistered;

        for(Contact contact : listContact){
            unregistered = true;
            for(User registeredUser : registeredUsers){
                if((StringUtils.hasText(registeredUser.getPhoneNo()))
                        &&(StringUtils.hasText(contact.getPhoneNo()))
                        &&(registeredUser.getPhoneNo().equals(contact.getPhoneNo()))){
                    unregistered = false;
                    break;
                }
            }
            if (unregistered) {
                User user = new User();
                user.setName(contact.getName());
                user.setPhoneNo(contact.getPhoneNo());
                unregisteredUsers.add(user);
                unregisteredPhoneNos.add(user.getPhoneNo());
            }
        }

        // 今天邀请过的手机号
        List<String> invitedPhoneNos = userFeignClient.hasInvitedToday(unregisteredPhoneNos
                .toArray(new String[unregisteredPhoneNos.size()])).getData();
        // 处理结果汇总
        PhoneAddressVO phoneAddressVO = new PhoneAddressVO();

        for (User user : unregisteredUsers) {
            PhoneAddressVO.UnregisteredUser unregisteredUser = new PhoneAddressVO.UnregisteredUser();
            unregisteredUser.setUser(user);
            unregisteredUser.setHasInvite(invitedPhoneNos.contains(user.getPhoneNo()) ? 1 : 0);
            phoneAddressVO.getUnregisteredUsers().add(unregisteredUser);
        }
        // 查找好友ID、包括黑名单ID
        List<String> friendIds = findFriendIds(userId, null);
        String[] registeredIds = registeredUsers.stream().map(User::getUserId).toArray(String[]::new);
        DataCounts counts = mutualFriendsCount(userId, registeredIds);
        for (User user : registeredUsers) {
            if (userId.equals(user.getUserId())) {
                continue;
            }
            if (friendIds.contains(user.getUserId())) {
                continue;
            }
            PhoneAddressVO.RegisteredUser registeredUser = new PhoneAddressVO.RegisteredUser();
            registeredUser.setUser(user);
            registeredUser.setMutualFriendCount(counts.getCount(user.getUserId()));
            // 处理好友关系
            HandleResult result = getFriendHandle(userId, user.getUserId());
            registeredUser.setHandleFlag(result.handleFlag);
            registeredUser.setConfirmId(result.confirmId);
            phoneAddressVO.getRegisteredUsers().add(registeredUser);
        }

        List<PhoneAddressVO.RegisteredUser> list = phoneAddressVO.getRegisteredUsers();
        Iterator<PhoneAddressVO.RegisteredUser> iterator = list.iterator();
        while (iterator.hasNext()) {
            PhoneAddressVO.RegisteredUser registeredUser = iterator.next();
            if (null == registeredUser) {
                iterator.remove();
            }

            if (null == registeredUser.getMutualFriendCount()) {
                registeredUser.setMutualFriendCount(0L);
            }
        }

        if (0 < list.size()) {
            list.sort(Comparator.comparing(
                    PhoneAddressVO.RegisteredUser::getMutualFriendCount).reversed());
        }

        //手动分页
        int registeredUserSize = phoneAddressVO.getRegisteredUsers().size();
        int unRegisteredUserSize = phoneAddressVO.getUnregisteredUsers().size();
        //总量
        int total = registeredUserSize + unRegisteredUserSize;

        int start = (currentPage - 1) * rows;
        int end = currentPage * rows;

        if(start > total){
            return new PhoneAddressVO();
        }

        if(end <= registeredUserSize){
            phoneAddressVO.setRegisteredUsers(phoneAddressVO.getRegisteredUsers()
                    .subList(start, end));
            phoneAddressVO.setUnregisteredUsers(new ArrayList<PhoneAddressVO.UnregisteredUser>());
            return phoneAddressVO;
        }

        if((start < registeredUserSize)
                &&(end <= total)){
            phoneAddressVO.setRegisteredUsers(phoneAddressVO.getRegisteredUsers()
                    .subList(start, registeredUserSize));
            phoneAddressVO.setUnregisteredUsers(phoneAddressVO.getUnregisteredUsers()
                    .subList(0, end - registeredUserSize));
            return phoneAddressVO;
        }

        if((start < registeredUserSize)
                &&(end > total)){
            phoneAddressVO.setRegisteredUsers(phoneAddressVO.getRegisteredUsers()
                    .subList(start, registeredUserSize));
            return phoneAddressVO;
        }

        if((start >= registeredUserSize)
                &&(end <= total)){
            phoneAddressVO.setRegisteredUsers(new ArrayList<PhoneAddressVO.RegisteredUser>());
            phoneAddressVO.setUnregisteredUsers(phoneAddressVO.getUnregisteredUsers()
                    .subList(start - registeredUserSize, end - registeredUserSize));
            return phoneAddressVO;
        }

        if((start >= registeredUserSize)
                &&(end > total)){
            phoneAddressVO.setRegisteredUsers(new ArrayList<PhoneAddressVO.RegisteredUser>());
            phoneAddressVO.setUnregisteredUsers(phoneAddressVO.getUnregisteredUsers().
                    subList(start, phoneAddressVO.getUnregisteredUsers().size()));
            return phoneAddressVO;
        }

        return phoneAddressVO;
    }

    /**
     * 移除coolfaceinfo
     * "coolfaceMe"类型的直接在APP端删除，不需要掉后台接口，因为只有在用户第一次登陆的时候才会出现
     * "coolfacedUserRegister"  传 CoolfaceNotice 的noticeId值
     * "coolfaceMeApplyToBeFriend" 传FriendsConfirm 的confirmId值
     * "recommandUser"类型的直接在APP端删除，不需要掉后台接口，因为只有在用户第一次登陆的时候才会出现
     *
     * @param infoType
     * @param id
     * @author lid
     * @date 2017.11.15
     */
    public void removeCoolfaceInfo(String infoType, String id) {
        if (!StringUtils.hasText(infoType)) {
            throw new AppException("消息类型为空!");
        }

        if (!StringUtils.hasText(id)) {
            throw new AppException("id为空!");
        }

        if (CoolfaceNoticeType.COOLFACEDUSERREGISTER.equals(infoType)) {
            //将我coolface过的的注册了的消息移除
            userFeignClient.readCoolfaceNotice(id);
            return;
        }

        if (CoolfaceNoticeType.COOLFACEMEAPPLYTOBEFRIEND.equals(infoType)) {
            friendsConfirmService.updateConfirm(id, null, 2);
            return;
        }
    }

    /**
     *
     *
     1，coolface推荐  （属于系统推荐用户，也就是系统挑选出若干可以推荐的照片放在首页（暂时未做））
     2，推荐好友 （通讯录的好友，好友的好友，附近的人，  infoType 为 recommandUser， 获取User 结构中的用户数据）
     3，Coolface推荐  （我以前找过的人注册了，我就会收到一条通知，这条通知就是Coolface推荐，
     infoType为 coolfacedUserRegister，获取coolfaceNotice结构中的数据）
     4，有人Coolface你 （有人coolface找到了我，并且添加我为好友，未开启自动确认加好友,
     那么我会收到一条coolface加好友的申请，infoType为coolfaceMeApplyToBeFriend,
     获取coolfaceRequestVo中的数据，其中：coolfaceRequestVo子结构friendsConfirm中的
     handleFlag字段标识请求的处理情况，0：未处理；1：已处理且接受；
     2：已处理且拒绝；0即对应《有人coolface你》UI图，等待你的请求确认；1为你开启了
     自动确认加好友，对应《自动确认加好友》UI图）
     5，自动确认加好友（参考第4点，从handleFlag字段中判断）

     6，确认加好友（你coolface别人并申请加好友，如果对方通过，那么会获得一条确认加好友的通知消息
     infoType为confirmToBeFriend，获取coolfaceNotice结构中的数据，
     此时双方已经是好友关系）
     */

    /**
     * 注册前有人coolface我             coolfaceMe
     确认加好友                       confirmToBeFriend
     我coolface过的注册了             coolfacedUserRegister
     coolface我并申请加我为好友        coolfaceMeApplyToBeFriend
     通讯录好友、好友的好友、附近的人     recommandUser
     */

    /**
     * 获取首页头部coolface消息
     *
     * @param userId
     * @param isFirstLogin 是否第一次登陆，（2获取测试数据 , 1是第一次登陆，0不是第一次登陆）
     * @author lid
     * @date 2017.11.14
     */
    public List<CoolfaceInfoVo> getIndexCoolfaceInfo(String userId, Integer isFirstLogin, Double userLatitude,
                                                     Double userLongitud, Integer distance) {

        List<CoolfaceInfoVo> listCoolfaceInfoVo = new ArrayList<>();
        if ((null != isFirstLogin)
                && (2 == isFirstLogin)) {
            //直接制造测试数据
            //1,用户是第一次登陆，获取谁coolface我
            FaceSearchUser faceSearchUser = new FaceSearchUser();
            faceSearchUser.setJobName("教师");
            faceSearchUser.setMsg("难以忘记初次见你，一双迷人的眼睛");
            faceSearchUser.setFacePicUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/166dycvpseyp8mudlyra.jpeg");
            faceSearchUser.setAddress("长沙梅溪湖");
            faceSearchUser.setBornDate(new Date());
            faceSearchUser.setCity("长沙");
            faceSearchUser.setFriendHandle(2);
            faceSearchUser.setGender(1);
            faceSearchUser.setImageUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1659on6pu279ake5otpa.png");
            faceSearchUser.setLatitude(28.200975);
            faceSearchUser.setLongitude(112.894831);
            faceSearchUser.setName("李杜");
            faceSearchUser.setProvince("湖南");
            faceSearchUser.setSimilarRate(80.88);
            faceSearchUser.setUserId("15zff7c7weth4n1ne92r");

            CoolfaceInfoVo vo1 = new CoolfaceInfoVo();
            vo1.setFriendId("15zff7c7weth4n1ne92r");
            //处理标志（0：未处理；1：已处理且接受；2：已处理且拒绝）
            vo1.setHandleFlag(0);
            vo1.setInfoType(CoolfaceNoticeType.COOLFACEME);
            vo1.setFaceSearchUser(faceSearchUser);
            vo1.setFriendProvince("湖南");
            vo1.setFriendCity("长沙");
            listCoolfaceInfoVo.add(vo1);

            //2,Coolface推荐我以前找过的人注册了，我就会收到一条通知，这条通知就是Coolface推荐，
            //infoType为 coolfacedUserRegister，获取coolfaceNotice结构中的数据
            CoolfaceNotice coolfaceNotice = new CoolfaceNotice();
            coolfaceNotice.setNoticeId("1");
            coolfaceNotice.setSimilarRate(88.88);
            coolfaceNotice.setNoticeUserImageUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1659on6pu279ake5otpa.png");
            coolfaceNotice.setNoticeUserName("李杜");
            coolfaceNotice.setNoticeUserGender(1);
            coolfaceNotice.setMsg("难以忘记初次见你，一双迷人的眼睛");
            coolfaceNotice.setJobName("教师");
            coolfaceNotice.setFriendHandle(1);
            coolfaceNotice.setFacePicUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/166dycvpseyp8mudlyra.jpeg");
            coolfaceNotice.setHasRead(0);
            coolfaceNotice.setNoticeType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
            coolfaceNotice.setNoticeUserId("15zffa3teapt95y7nss5");
            coolfaceNotice.setUserId("15zff7c7weth4n1ne92r");
            coolfaceNotice.setBornDate(new Date());
            coolfaceNotice.setCreateDate(new Date());
            CoolfaceInfoVo coolfaceInfoVo = new CoolfaceInfoVo();
            coolfaceInfoVo.setInfoType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
            coolfaceInfoVo.setCoolfaceNotice(coolfaceNotice);
            coolfaceInfoVo.setFriendId(coolfaceNotice.getNoticeUserId());
            coolfaceInfoVo.setHandleFlag(0);

            coolfaceInfoVo.setFriendProvince("湖南");
            coolfaceInfoVo.setFriendCity("长沙");

            listCoolfaceInfoVo.add(coolfaceInfoVo);

            //3,有人coolface找到了我，并且添加我为好友,
            // infoType为coolfaceMeApplyToBeFriend
            CoolfaceRequestVo coolfaceRequestVo = new CoolfaceRequestVo();
            FriendsConfirm friendsConfirm = new FriendsConfirm();
            friendsConfirm.setSearchId("123456789");
            friendsConfirm.setCreateTime(new Date());
            friendsConfirm.setFriendId("12345667");
            friendsConfirm.setHandleFlag(0);
            friendsConfirm.setConfirmId("1234567");
            friendsConfirm.setNotice("你好!");
            friendsConfirm.setUserImageUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/160k3jrlr0j7fpxb8yz2.jpg");

            FaceSearch faceSearch = new FaceSearch();
            faceSearch.setSearchTime(new Date());
            faceSearch.setDistance("10000");
            faceSearch.setFacePicUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/166dycvpseyp8mudlyra.jpeg");
            faceSearch.setFriendId("15zff7c7weth4n1ne92r");
            faceSearch.setFriendName("李杜");
            faceSearch.setLatitude(28.199073);
            faceSearch.setLongitude(112.897856);
            faceSearch.setMark("长沙梅溪湖");
            faceSearch.setMsg("千年等一回");
            faceSearch.setPlace("长沙市岳麓区");
            faceSearch.setSearchType(1);
            faceSearch.setSimilarity(88.88f);
            faceSearch.setUserId("15zounp387shkgrzsx40");
            coolfaceRequestVo.setFriendsConfirm(friendsConfirm);
            coolfaceRequestVo.setFaceSearch(faceSearch);
            CoolfaceInfoVo vo2 = new CoolfaceInfoVo();
            vo2.setCoolfaceRequestVo(coolfaceRequestVo);
            vo2.setInfoType(CoolfaceNoticeType.COOLFACEMEAPPLYTOBEFRIEND);
            vo2.setFriendId(coolfaceRequestVo.getFriendsConfirm().getFriendId());
            vo2.setHandleFlag(coolfaceRequestVo.getFriendsConfirm().getHandleFlag());
            vo2.setFriendProvince("湖南");
            vo2.setFriendCity("长沙");
            listCoolfaceInfoVo.add(vo2);

            //4,自动确认加好友  有人coolface找到了我，并且添加我为好友,我开启了自动确认加好友
            // infoType为coolfaceMeApplyToBeFriend
            FriendsConfirm friendsConfirm1 = new FriendsConfirm();
            friendsConfirm1.setSearchId("123456789");
            friendsConfirm1.setCreateTime(new Date());
            friendsConfirm1.setFriendId("12345667");
            friendsConfirm1.setConfirmId("1234567");
            friendsConfirm1.setNotice("你好!");
            friendsConfirm1.setHandleFlag(1);
            friendsConfirm1.setUserImageUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1659on6pu279ake5otpa.png");
            coolfaceRequestVo.setFriendsConfirm(friendsConfirm1);

            CoolfaceInfoVo vo3 = new CoolfaceInfoVo();
            vo3.setCoolfaceRequestVo(coolfaceRequestVo);
            vo3.setInfoType(CoolfaceNoticeType.COOLFACEMEAPPLYTOBEFRIEND);
            vo3.setFriendId(coolfaceRequestVo.getFriendsConfirm().getFriendId());
            vo3.setHandleFlag(coolfaceRequestVo.getFriendsConfirm().getHandleFlag());
            vo3.setFriendProvince("湖南");
            vo3.setFriendCity("长沙");
            vo3.setInfoType(CoolfaceNoticeType.COOLFACEMEAPPLYTOBEFRIEND);
            vo3.setHandleFlag(1);
            listCoolfaceInfoVo.add(vo3);

            //5,确认加好友
            //你coolface别人并申请加好友，如果对方通过，那么会获得一条确认加好友的通知消息
            //infoType为confirmToBeFriend，获取coolfaceNotice结构中的数据，
            //此时双方已经是好友关系
            CoolfaceInfoVo coolfaceInfoVo1 = new CoolfaceInfoVo();
            coolfaceInfoVo1.setInfoType(CoolfaceNoticeType.CONFIRMTOBEFRIEND);

            CoolfaceNotice coolfaceNotice1 = new CoolfaceNotice();
            coolfaceNotice1.setNoticeId("1");
            coolfaceNotice1.setSimilarRate(88.88);
            coolfaceNotice1.setNoticeUserImageUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1659on6pu279ake5otpa.png");
            coolfaceNotice1.setNoticeUserName("李杜");
            coolfaceNotice1.setNoticeUserGender(1);
            coolfaceNotice1.setMsg("难以忘记初次见你，一双迷人的眼睛");
            coolfaceNotice1.setJobName("教师");
            coolfaceNotice1.setFriendHandle(1);
            coolfaceNotice1.setFacePicUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/166dycvpseyp8mudlyra.jpeg");
            coolfaceNotice1.setHasRead(0);
            coolfaceNotice1.setNoticeType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
            coolfaceNotice1.setNoticeUserId("15zffa3teapt95y7nss5");
            coolfaceNotice1.setUserId("15zff7c7weth4n1ne92r");
            coolfaceNotice1.setBornDate(new Date());
            coolfaceNotice1.setCreateDate(new Date());

            coolfaceInfoVo1.setCoolfaceNotice(coolfaceNotice1);
            coolfaceInfoVo1.setFriendId(coolfaceNotice.getNoticeUserId());
            coolfaceInfoVo1.setHandleFlag(1);
            coolfaceInfoVo1.setFriendProvince("湖南");
            coolfaceInfoVo1.setFriendCity("长沙");
            listCoolfaceInfoVo.add(coolfaceInfoVo1);

            return listCoolfaceInfoVo;
        }

        /********************构造数据分割线，以下为真实数据************************/
        //listNoticeUserId去重
        List<String> listNoticeUserId = new ArrayList<>();
        //放入自己的id，
        listNoticeUserId.add(userId);

        if ((null != isFirstLogin)
                && (1 == isFirstLogin)) {
            //用户是第一次登陆，获取谁coolface我
            logger.info("当前用户第一次登陆!");
            AppSearchResult appSearchResult = new AppSearchResult();
            try {
                appSearchResult = faceSearchService.whoCoolfaceMe(userId);
            } catch (Exception e) {
                logger.info(e.getMessage());
            }

            if (null != appSearchResult) {
                List<FaceSearchUser> listFaceSearchUser = appSearchResult.getUsers();
                if ((null != listFaceSearchUser)
                        && (0 < listFaceSearchUser.size())) {

                    User user = userFeignClient.getUser(userId).getData();
                    if (null == user) {
                        throw new AppException("未找到当前用户!");
                    }

                    logger.info("以前有人找过我，给搜索我的人发送通知!");

                    for (FaceSearchUser faceSearchUser : listFaceSearchUser) {
                        if (userId.equals(faceSearchUser.getUserId())) {
                            //自己搜到了自己，好像只有在开发和测试的情况下才出现，真实情况应该不存在这种情况
                            //但是还是做一下处理，以防万一
                            continue;
                        }

                        //只推送一次
                        if (listNoticeUserId.contains(faceSearchUser.getUserId())) {
                            continue;
                        }

                        CoolfaceInfoVo vo = new CoolfaceInfoVo();
                        vo.setInfoType(CoolfaceNoticeType.COOLFACEME);
                        vo.setFaceSearchUser(faceSearchUser);
                        vo.setHandleFlag(0);
                        vo.setFriendId(faceSearchUser.getUserId());
                        vo.setFriendProvince(faceSearchUser.getProvince());
                        vo.setFriendCity(faceSearchUser.getCity());
                        listCoolfaceInfoVo.add(vo);

                        //保存给他人的通知（通知别人你以前coolface的用户注册了）
                        CoolfaceNotice notice = new CoolfaceNotice();
                        notice.setUserId(faceSearchUser.getUserId());
                        notice.setNoticeUserId(userId);

                        //消息通知的类型为coolfacedUserRegister
                        notice.setNoticeType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
                        notice.setHasRead(0);
                        notice.setNoticeId(GlobalIdWorker.nextString());
                        notice.setCreateDate(new Date());
                        notice.setBornDate(new Date(user.getBornDate().getTime()));
                        notice.setConfirmId(faceSearchUser.getConfirmId());
                        notice.setFacePicUrl(faceSearchUser.getFacePicUrl());
                        notice.setFriendHandle(faceSearchUser.getFriendHandle());
                        notice.setJobName(user.getJobName());
                        notice.setMsg(faceSearchUser.getMsg());
                        notice.setNoticeUserGender(user.getGender());
                        notice.setNoticeUserName(user.getName());
                        notice.setNoticeUserImageUrl(user.getImageUrl());
                        notice.setSimilarRate(faceSearchUser.getSimilarRate());
                        notice.setNoticeUserProvince(user.getProvince());
                        notice.setNoticeUserCity(user.getCity());
                        userFeignClient.saveNotice(notice);
                        logger.info("coolface通知保存成功！");
                        logger.info(faceSearchUser.getName());
                        logger.info(faceSearchUser.getUserId() + "," + faceSearchUser.getNoticeRegId());

                        CoolfaceInfoVo coolfaceInfoVo = new CoolfaceInfoVo();

                        coolfaceInfoVo.setInfoType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
                        coolfaceInfoVo.setCoolfaceNotice(notice);
                        coolfaceInfoVo.setHandleFlag(0);
                        coolfaceInfoVo.setFriendId(notice.getNoticeUserId());
                        coolfaceInfoVo.setFriendProvince(notice.getNoticeUserProvince());
                        coolfaceInfoVo.setFriendCity(notice.getNoticeUserCity());

                        CoolfacePushVo coolfacePushVo = new CoolfacePushVo();
                        coolfacePushVo.setType(PushTypeStaticVo.INDEXPUSH);
                        coolfacePushVo.setCoolfaceInfoVo(coolfaceInfoVo);
                        String pushMsgType = JsonConverter.toJson(coolfacePushVo);
                        logger.info("pushMsgType:"+pushMsgType);

                        //推送消息
                        forumClient.pushMessageForExtraMsg(faceSearchUser.getUserId(),
                                FriendsConfirmService.TITLE, FriendsConfirmService.COOLFACEDUSERREGISTERMSG,
                                pushMsgType);
                        listNoticeUserId.add(faceSearchUser.getUserId());
                    }
                }
            }
        } else {
            logger.info("当前用户不是第一次登陆!");
            //不是第一次登陆，获取coolface推荐，也就是从coolface通知中获取我的通知
            List<CoolfaceNotice> listCoolfaceNotice = userFeignClient.getNotice().getData();
            if ((null != listCoolfaceNotice)
                    && (0 < listCoolfaceNotice.size())) {

                logger.info("listCoolfaceNotice.size():" + listCoolfaceNotice.size());

                for (CoolfaceNotice coolfaceNotice : listCoolfaceNotice) {

                    if (CoolfaceNoticeType.COOLFACEDUSERREGISTER.equals(coolfaceNotice.getNoticeType())) {

                        if ((!StringUtils.hasText(coolfaceNotice.getNoticeUserId()))
                                || (listNoticeUserId.contains(coolfaceNotice.getNoticeUserId()))) {
                            continue;
                        }

                        CoolfaceInfoVo vo = new CoolfaceInfoVo();
                        vo.setInfoType(CoolfaceNoticeType.COOLFACEDUSERREGISTER);
                        vo.setCoolfaceNotice(coolfaceNotice);
                        vo.setHandleFlag(coolfaceNotice.getFriendHandle());
                        vo.setFriendId(coolfaceNotice.getNoticeUserId());
                        vo.setFriendProvince(coolfaceNotice.getNoticeUserProvince());
                        vo.setFriendCity(coolfaceNotice.getNoticeUserCity());
                        listCoolfaceInfoVo.add(vo);
                        listNoticeUserId.add(coolfaceNotice.getNoticeUserId());
                        continue;
                    }

                    if (CoolfaceNoticeType.CONFIRMTOBEFRIEND.equals(coolfaceNotice.getNoticeType())) {
                        if ((!StringUtils.hasText(coolfaceNotice.getNoticeUserId()))
                                || (listNoticeUserId.contains(coolfaceNotice.getNoticeUserId()))) {
                            continue;
                        }

                        CoolfaceInfoVo vo = new CoolfaceInfoVo();
                        vo.setInfoType(CoolfaceNoticeType.CONFIRMTOBEFRIEND);
                        vo.setCoolfaceNotice(coolfaceNotice);
                        vo.setHandleFlag(coolfaceNotice.getFriendHandle());
                        vo.setFriendId(coolfaceNotice.getNoticeUserId());
                        vo.setFriendProvince(coolfaceNotice.getNoticeUserProvince());
                        vo.setFriendCity(coolfaceNotice.getNoticeUserCity());
                        listCoolfaceInfoVo.add(vo);
                        listNoticeUserId.add(coolfaceNotice.getNoticeUserId());
                        continue;
                    }
                }
            }

            //获取我的coolface加好友申请
            List<CoolfaceRequestVo> listCoolfaceRequestVo = friendsConfirmService.getCoolfaceRequest(userId);
            if ((null != listCoolfaceRequestVo)
                    && (0 < listCoolfaceRequestVo.size())) {
                logger.info("listCoolfaceRequestVo.size():" + listCoolfaceRequestVo.size());
                for (CoolfaceRequestVo coolfaceRequestVo : listCoolfaceRequestVo) {
                    if ((!StringUtils.hasText(coolfaceRequestVo.getFriendsConfirm().getUserId()))
                            || (listNoticeUserId.contains(coolfaceRequestVo.getFriendsConfirm().getUserId()))) {
                        continue;
                    }

                    User friend = userFeignClient.getUser(coolfaceRequestVo.getFriendsConfirm().getUserId()).getData();
                    if (null == friend) {
                        continue;
                    }
                    CoolfaceInfoVo vo = new CoolfaceInfoVo();
                    vo.setInfoType(CoolfaceNoticeType.COOLFACEMEAPPLYTOBEFRIEND);
                    vo.setCoolfaceRequestVo(coolfaceRequestVo);
                    vo.setFriendId(coolfaceRequestVo.getFriendsConfirm().getUserId());
                    vo.setHandleFlag(coolfaceRequestVo.getFriendsConfirm().getHandleFlag());
                    vo.setFriendProvince(friend.getProvince());
                    vo.setFriendCity(friend.getCity());
                    listCoolfaceInfoVo.add(vo);
                    listNoticeUserId.add(coolfaceRequestVo.getFriendsConfirm().getUserId());
                }
            }
        }

        return listCoolfaceInfoVo;
    }

    /**
     * 获取我的好友的好友（limit20），最多获取20个
     *
     * @param userId
     * @param friendIds
     * @return List<String>
     * @author lid
     * @date 2017.11.14
     */
    public List<String> getMyFriendsFriends(String userId, List<String> friendIds) {
        logger.info("获取20个好友的好友id");
        if (!StringUtils.hasText(userId)) {
            return null;
        }

        if ((null == friendIds)
                || (0 == friendIds.size())) {
            return null;
        }
        try {
            return queryFactory.select(qFriends.friendId)
                    .from(qFriends)
                    .where(qFriends.userId.in(friendIds))
                    .where(qFriends.friendId.notIn(friendIds))
                    .limit(20)
                    .fetch();
        } catch (Exception e) {
            logger.info(e.getMessage());
            return null;
        }
    }
}